/**
* Javscript Source code file for combat_reports.php
*/

//global variable for this screen
var selected_key = 0;
var data_grid = null;
var published_keys = new Array();
var filter_active = false;
var filter = new Array(3);
var current_filter_value = new Array(3);
var report_store = null;
var ignore_next_fetch = false;
var galaxytool_selected_rows = 0;
// var galaxytool_userid = ; <-- defined at php file
// var store_url = "<?php echo $store_url; ?>"; <-- defined at php file

function galaxytool_cr_init() {
	// register method for onKeyPress for search form
	dojo.connect(dijit.byId("attacker"), "onKeyPress", galaxytool_handle_searchchange );
	dojo.connect(dijit.byId("defender"), "onKeyPress", galaxytool_handle_searchchange );
	dojo.connect(dijit.byId("search_button"), "onClick", galaxytool_search );
	dojo.connect(dijit.byId("reset_button"), "onClick", galaxytool_reset );
	dojo.connect(dijit.byId("download_button"), "onClick", galaxytool_cr_download );

	dojo.connect(dijit.byId("publish_all_button"), "onClick", galaxytool_publish_selected );
	dojo.connect(dijit.byId("unpublish_all_button"), "onClick", galaxytool_unpublish_selected );
	dojo.connect(dijit.byId("delete_all_button"), "onClick", galaxytool_delete_selected );

	dojo.connect(dijit.byId("publish_button"), "onClick", galaxytool_publish_single );
	dojo.connect(dijit.byId("unpublish_button"), "onClick", galaxytool_unpublish_single );
	dojo.connect(dijit.byId("delete_button"), "onClick", galaxytool_delete_single );

	var grid1_ref = dijit.byId("grid1");
	dojo.connect(grid1_ref, "_onFetchComplete", galaxytool_grid_on_fetch_complete );
	dojo.connect(grid1_ref, "onRowClick", galaxytool_handleRowSelect );
	dojo.connect(grid1_ref, "onFetchError", handle_dojo_errors );
	try {
	dijit.byId("coordinates").validator = galaxytool_coordinate_input;
	} catch(e) {
		console.log(e);
	}
}
dojo.ready(galaxytool_cr_init);

function galaxytool_handle_searchchange(e) {
	if (e != null && e.keyCode != 13) {
		return; // ignore onKeyPress event if other keys than ENTER are hit
	}
	// submit form
	galaxytool_search();
}

function galaxytool_handleRowSelect(e) {	
	// get combat report id
	var item  = e.grid.getItem(e.rowIndex);
	var value = e.grid.store.getValue(item, "id");
	
	// get selection value if checkbox was clicked
	if (e.target.type == "checkbox") {
		if (e.grid.store.getValues(item,"selected") == "true") {
			galaxytool_selected_rows++;
		} else {
			galaxytool_selected_rows--;
		}
		
		if (galaxytool_selected_rows > 1) {
			galaxytool_calculated_content();
			return;
		}
	}

	if (selected_key == value) return; // no refresh needed
	selected_key = value;
	data_grid = e.grid;

	galaxytool_load_content(value);
}

function galaxytool_load_content(value) {
	// load combat report into detail area	
	dojo.byId("summary_area").style.display = "none";
	
	var source_url = "ajax/ajax_combat_reports.php?type=content&id="+value;
	var i;
	var xhrArgs = {
	        url: source_url,
	        handleAs: "json",
	        load: function(jsonData) {
	        	if (jsonData.messages != null) {
	        		showMessages(jsonData.messages);
	        	} else {
	        		try {
	    				dojo.byId("details_area").style.display = "";
	    				dojo.byId("details_area").style.visibility = "visible";
	    				
    					var ResponseObject = jsonData;

	    				var attacker = "";
	    				var defender = "";
	    				var attacker_text = "";
	    				var defender_text = "";
	    				var a_techs = new Array(3);
	    				var d_techs = new Array(3);
	    				var a_lost = 0;
	    				var d_lost = 0;
	    				var coords = null;

	    				for (i=0; i<ResponseObject.attacker.length; i++) {
	    					if (attacker != "") {
	    						attacker += "<br>";
	    						attacker_text += ", ";
	    					}
	    					attacker_text += ResponseObject.attacker[i].playername;
	    					attacker += "<a class=\"link\" href=\"playerinformation.php?id="+ResponseObject.attacker[i].playerid+"\">"+ResponseObject.attacker[i].playername+"</a>";

	    					coords = ResponseObject.attacker[i].coords.split(":");
	    					attacker += " [<a class=\"link\" href=\"galaxyview.php?gala="+coords[0]+"&system="+coords[1]+"\">"+ResponseObject.attacker[i].coords+"</a>]";
	    					a_techs[0] = ResponseObject.attacker[i].tech.w;
	    					a_techs[1] = ResponseObject.attacker[i].tech.s;
	    					a_techs[2] = ResponseObject.attacker[i].tech.a;
	    					a_lost     = ResponseObject.attacker[i].lost;
	    				}

	    				for (i=0; i<ResponseObject.defender.length; i++) {
	    					if (defender != "") {
	    						defender += "<br>";
	    						defender_text += ", ";
	    					}
	    					defender_text += ResponseObject.defender[i].playername;
	    					defender += "<a class=\"link\" href=\"playerinformation.php?id="+ResponseObject.defender[i].playerid+"\">"+ResponseObject.defender[i].playername+"</a>";

	    					coords = ResponseObject.defender[i].coords.split(":");
	    					defender += " [<a class=\"link\" href=\"galaxyview.php?gala="+coords[0]+"&system="+coords[1]+"\">"+ResponseObject.defender[i].coords+"</a>]";
	    					d_techs[0] = ResponseObject.defender[i].tech.w;
	    					d_techs[1] = ResponseObject.defender[i].tech.s;
	    					d_techs[2] = ResponseObject.defender[i].tech.a;
	    					d_lost     = ResponseObject.defender[i].lost;
	    				}
	    				dojo.byId("attackername").innerHTML       = attacker;
	    				dojo.byId("defendername").innerHTML       = defender;


	    				dojo.byId("combattime").innerHTML         = ResponseObject.combattime;
	    				dojo.byId("att_lost_units").innerHTML     = a_lost;
	    				dojo.byId("def_lost_units").innerHTML     = d_lost;

	    				dojo.byId("att_weapon").innerHTML         = a_techs[0];
	    				dojo.byId("att_shield").innerHTML         = a_techs[1];
	    				dojo.byId("att_amour").innerHTML          = a_techs[2];
	    				dojo.byId("def_weapon").innerHTML         = d_techs[0];
	    				dojo.byId("def_shield").innerHTML         = d_techs[1];
	    				dojo.byId("def_amour").innerHTML          = d_techs[2];


	    				dojo.byId("loot_metal").innerHTML         = ResponseObject.loot.m;
	    				dojo.byId("loot_crystal").innerHTML       = ResponseObject.loot.c;
	    				dojo.byId("loot_deuterium").innerHTML     = ResponseObject.loot.d;
	    				dojo.byId("debris_metal").innerHTML       = ResponseObject.debris.m;
	    				dojo.byId("debris_crystal").innerHTML     = ResponseObject.debris.c;
	    				dojo.byId("combat_coordinates").innerHTML = ResponseObject.c_coords;

	    				if (ResponseObject.winner == "attacker") {
	    					dojo.byId("winner_name").innerHTML    = attacker_text;
	    				} else if (ResponseObject.winner == "defender") {
	    					dojo.byId("winner_name").innerHTML    = defender_text;
	    				} else {
	    					dojo.byId("winner_name").innerHTML    = "-";
	    				}

	    			} catch(e) {
	    				console.log("error:");
	    				console.log(e);
	    			}

	    			if (published_keys[selected_key] == true) {
	    				dijit.byId("publish_button").set('disabled', true);
	    				dijit.byId("publish_button").set('style', "display:none");
	    				dijit.byId("unpublish_button").set('style', "display:inline-block");
	    				dijit.byId("unpublish_button").set('disabled', false);
	    				dijit.byId("delete_button").set('disabled', false);
	    			} else if (published_keys[selected_key] == "private") {
	    				dijit.byId("publish_button").set('style', "display:inline-block");
	    				dijit.byId("publish_button").set('disabled', true);
	    				dijit.byId("unpublish_button").set('style', "display:none");
	    				dijit.byId("unpublish_button").set('disabled', true);
	    				dijit.byId("delete_button").set('disabled', true);
	    			} else {
	    				dijit.byId("publish_button").set('style', "display:inline-block");
	    				dijit.byId("publish_button").set('disabled', false);
	    				dijit.byId("unpublish_button").set('style', "display:none");
	    				dijit.byId("unpublish_button").set('disabled', true);
	    				dijit.byId("delete_button").set('disabled', false);
	    			}
	        	}

	        },
	        error: function(error) {
				console.log("Error:");
				console.log(error);
	        }
	}	
	dojo.xhrGet(xhrArgs);

}

function galaxytool_calculated_content() {
	dojo.byId("details_area").style.display = "none";
	dojo.byId("details_area").style.visibility = "hidden";
	dojo.byId("summary_area").style.display = "";
	dojo.byId("summary_area").style.visibility = "";
	
	var item           = null;
	var loot_metal     = 0;
	var loot_crystal   = 0;
	var loot_deuterium = 0;
	var debris_metal   = 0;
	var debris_crystal = 0;
	
	for (var i=0; i<grid1.get("rowCount"); i++) {
		item = grid1.getItem(i);
		if (item != null) {
			if (store1.getValues(item,"selected") == "true") {
				loot_metal     += parseInt(store1.getValues(item,"loot_m"));
				loot_crystal   += parseInt(store1.getValues(item,"loot_c"));
				loot_deuterium += parseInt(store1.getValues(item,"loot_d"));
				
				debris_metal   += parseInt(store1.getValues(item,"debris_m"));
				debris_crystal += parseInt(store1.getValues(item,"debris_c"));
			}
		}
	}

	dojo.byId("summary_loot_metal").innerHTML     = NumberFormat(loot_metal);
	dojo.byId("summary_loot_crystal").innerHTML   = NumberFormat(loot_crystal);
	dojo.byId("summary_loot_deuterium").innerHTML = NumberFormat(loot_deuterium);
	dojo.byId("summary_debris_metal").innerHTML   = NumberFormat(debris_metal);
	dojo.byId("summary_debris_crystal").innerHTML = NumberFormat(debris_crystal);
}

function galaxytool_grid_formatter(val, rowIdx, cell) {
	var winner = store1.getValues(grid1.getItem(rowIdx),"winner");

	if (cell.field == "attacker") {
		if (winner == "attacker") {
			cell.customClasses.push("combat_winner");
		} else if (winner == "defender") {
			cell.customClasses.push("combat_looser");
		}
	} else {
		// cell is defender
		if (winner == "attacker") {
			cell.customClasses.push("combat_looser");
		} else if (winner == "defender") {
			cell.customClasses.push("combat_winner");
		}
	}
	return val;
}

function handle_dojo_errors(e) {
	console.log("fetch error:");
	console.log(e);
}

function checkbox_selection(selection) {
	var item = null;
	var id = null;
	
	for (var i=0; i<grid1.get("rowCount"); i++) {
		item = grid1.getItem(i);
		if (item != null) {
			if (i == 0) id = store1.getValues(item,"id");
			if (store1.getValues(item,"selected") == "true") {
				if (selection != true) {
					// remove selection
					store1.setValues(item,"selected",false);
					galaxytool_selected_rows--;
				}
			} else {
				if (selection == true) {
					// add selection
					store1.setValues(item,"selected",true);
					galaxytool_selected_rows++;
				}
			}
		}
	}
	if (galaxytool_selected_rows > 1) {
		galaxytool_calculated_content();
	} else if (galaxytool_selected_rows == 1) {
		galaxytool_load_content(id);
	}
}

function galaxytool_reload_grid(url) {
	// reset variables
	var selected_key = 0;
	var published_keys = new Array();
	var report_store = null;

	// store will trigger a refresh after REVERT has been called - we must ignore this, otherwise we will try to reload deleted items
	ignore_next_fetch = true;
	// reload content from URL
	store1.url = url;
	store1.revert(); // discard changes (checkboxes)
	store1.close();
	ignore_next_fetch = false; // just to be sure in case DOJO removes the fetch_complete event at REVERT()
	grid1.setStore(store1);
}

function galaxytool_publish_helper(publish_type) {
	if (publish_type != "publish" && publish_type != "unpublish" && publish_type != "delete") return false;

	// collect all keys
	var item = null;
	var selected_for_update = new Array();

	for (var i=0; i<grid1.get("rowCount"); i++) {
		item = grid1.getItem(i);
		if (item != null) {
			if (store1.getValues(item,"selected") == "true") {
				selected_for_update.push(store1.getValues(item,"id"));
			}
		}
	}
	if (selected_for_update.length < 1) return;

	var ids = "";
	for (var i=0; i < selected_for_update.length; i++) {
		ids += selected_for_update[i]
		if (i < (selected_for_update.length - 1)) {
			ids += "|";
		}
	}

	var source_url = "ajax/ajax_combat_reports.php?type="+publish_type;
	var xhrArgs = {
	        url: source_url,
	        content : {
	        	"id" : ids
	    		},
	        handleAs: "json",
	        load: function(jsonData) {
	        	if (jsonData.messages != null) {
	        		showMessages(jsonData.messages);
	        	} else {
	        		grid1.selection.deselectAll();
					galaxytool_reload_grid(store_url);
	        	}

	        },
	        error: function(error) {
				console.log("Error:");
				console.log(error);
	        }
	}	
	dojo.xhrPost(xhrArgs);
	
}

function get_search_source_url(type) {
	// get selection variables
	var attacker_name    = dojo.byId("attacker").value;
	var defender_name    = dojo.byId("defender").value;
	var owner_id         = dijit.byId("owner").get("value");

	try {
		var date_from = dojo.date.locale.format(dijit.byId("date_from").get("value"), {datePattern: 'yyyy-MM-dd', selector:'date'})
	} catch(e) {
		// error while grabbing select option -> ignore this (can happen for
		// invalid or empty date inputs)
		var date_from = "";
	}
	try {
		var date_to   = dojo.date.locale.format(dijit.byId("date_to").get("value"), {datePattern: 'yyyy-MM-dd', selector:'date'})
	} catch(e) {
		// error while grabbing select option -> ignore this (can happen for
		// invalid or empty date inputs)
		var date_to = "";
	}

	var public_reports   = "undefined";
	if (dijit.byId("public_yes").get("checked") == true) {
		public_reports = "true";
	} else if (dijit.byId("public_no").get("checked") == true) {
		public_reports = "false";
	}

	var coordinates = dijit.byId("coordinates").get("value");
	// validate coordinates before submitting search requests
	if (galaxytool_coordinate_input(coordinates,null) != true) return false;


	owner_id = (owner_id == 0) ? "" : owner_id;

	var source_url = "ajax/ajax_combat_reports.php?type="+type+
	"&attacker_name="+escape(attacker_name)+
	"&defender_name="+escape(defender_name)+
	"&owner_id="+owner_id+
	"&public_reports="+public_reports+
	"&date_from="+date_from+
	"&date_to="+date_to+
	"&coordinates="+coordinates;
	
	return source_url;
}

function galaxytool_search() {
	var source_url = get_search_source_url("search");

	galaxytool_reload_grid(source_url);
	store_url = source_url;

	dojo.byId("details_area").style.display = "none";
	dojo.byId("details_area").style.visibility = "hidden";
	dojo.byId("result_grid").style.visibility = "";

}

function galaxytool_cr_download() {
	var url = get_search_source_url("download");
	window.location.href = url;
}

function galaxytool_reset() {
	dojo.byId("attacker").value = "";
	dojo.byId("defender").value = "";
	dijit.byId("owner").set("value",0);
	dijit.byId("public_yes").set("checked",false);
	dijit.byId("public_no").set("checked",false);
	dojo.byId("date_from").value = "";
	dojo.byId("date_to").value = "";
	dojo.byId("coordinates").value = "";
}

function galaxytool_public_search(id) {
	var new_value = dijit.byId(id).get("checked");

	// ignore cases when checkbox is unchecked
	if (new_value == true) {
		if (id == "public_yes") {
			dijit.byId("public_no").set("checked",false);
		} else {
			dijit.byId("public_yes").set("checked",false);
		}
	}
}

function galaxytool_publish_selected() {
	galaxytool_publish_helper("publish");
}
function galaxytool_unpublish_selected() {
	galaxytool_publish_helper("unpublish");
}
function galaxytool_delete_selected() {
	galaxytool_publish_helper("delete");
}

function galaxytool_delete_single() {
	// disable buttons and cleanup details area (no combat report will be selected)
	dijit.byId("publish_button").set('disabled', true);
	dijit.byId("unpublish_button").set('disabled', true);
	dijit.byId("publish_button").set('style', "display: inline-block");
	dijit.byId("unpublish_button").set('style', "display: none");
	dijit.byId("delete_button").set('disabled', true);

	var source_url = "ajax/ajax_combat_reports.php?type=delete&id="+selected_key;
	var xhrArgs = {
	        url: source_url,
	        content : {
	        	"id" : selected_key
	    		},
	        handleAs: "json",
	        load: function(jsonData) {
	        	if (jsonData.messages != null) {
	        		showMessages(jsonData.messages);
	        	} else {
	        		// reload grid pane by deleting item from grid
					var items = grid1.selection.getSelected();
					if (items.length) {
						dojo.forEach(items, function(selectedItem) {
							if (selectedItem !== null) {
								store1.deleteItem(selectedItem);

								// select new first item
								grid1.selection.addToSelection(0);

								// get combat id
								var value = grid1.store.getValue(grid1.selection.getFirstSelected(), "id");
								//data_grid = grid1;

								// load content if data selection has changed since last fetch
								if (value != null && selected_key != value) {
									galaxytool_load_content(value);
								}
							}
						});
					}
	        	}

	        },
	        error: function(error) {
				console.log("Error:");
				console.log(error);
	        }
	}	
	dojo.xhrPost(xhrArgs);
	
}

function galaxytool_unpublish_single() {
	// disable button
	dijit.byId("unpublish_button").set('disabled', true);
	dijit.byId("unpublish_button").set('style', "display:none");
	// enable publish button
	dijit.byId("publish_button").set('style', "display:inline-block");
	dijit.byId("publish_button").set('disabled', false);

	var source_url = "ajax/ajax_combat_reports.php?type=unpublish&id="+selected_key;
	var xhrArgs = {
	        url: source_url,
	        content : {
	        	"id" : selected_key
	    		},
	        handleAs: "json",
	        load: function(jsonData) {
	        	if (jsonData.messages != null) {
	        		showMessages(jsonData.messages);
	        	} else {
	        		// store unpublished id to disable button for this combat report until page is left
					published_keys[selected_key] = null;
	        	}

	        },
	        error: function(error) {
				console.log("Error:");
				console.log(error);
	        }
	}	
	dojo.xhrPost(xhrArgs);
}

function galaxytool_publish_single() {
	// disable button
	dijit.byId("publish_button").set('disabled', true);
	dijit.byId("publish_button").set('style', "display:none");
	// enable unpublish button
	dijit.byId("unpublish_button").set('style', "display:inline-block");
	dijit.byId("unpublish_button").set('disabled', false);

	var source_url = "ajax/ajax_combat_reports.php?type=publish&id="+selected_key;
	var xhrArgs = {
	        url: source_url,
	        content : {
	        	"id" : selected_key
	    		},
	        handleAs: "json",
	        load: function(jsonData) {
	        	if (jsonData.messages != null) {
	        		showMessages(jsonData.messages);
	        	} else {
	        		// store published id to disable button for this combat report until page is left
					published_keys[selected_key] = true;
	        	}

	        },
	        error: function(error) {
				console.log("Error:");
				console.log(error);
	        }
	}	
	dojo.xhrPost(xhrArgs);

}

function galaxytool_grid_on_fetch_complete() {
	if (ignore_next_fetch == true) {
		ignore_next_fetch = false;
		return;
	}
	if (grid1.get("rowCount") > 0) {
		// select first item when fetch is complete
		grid1.selection.addToSelection(0);

		// get combat id
		var value = grid1.store.getValue(grid1.selection.getFirstSelected(), "id");
		//data_grid = grid1;

		// load content if data selection has changed since last fetch
		if (value != null && selected_key != value) {
			galaxytool_load_content(value);
		}

		selected_key = value;

		// collect public combat reports
		for (var i=0; i<grid1.get("rowCount"); i++) {
			if (grid1.getItem(i) != null) {
				if (store1.getValues(grid1.getItem(i),"public") == "true") {

					if (store1.getValues(grid1.getItem(i),"userid") == galaxytool_userid) {
						published_keys[store1.getValues(grid1.getItem(i),"id")] = true;
					} else {
						published_keys[store1.getValues(grid1.getItem(i),"id")] = "private";
					}
				} else {
					published_keys[store1.getValues(grid1.getItem(i),"id")] = null;
				}
			}
		}

	} else {
		grid1.selection.deselectAll();
		selected_key= null;

		// disable buttons and cleanup details area (no combat report is selected)
		dijit.byId("publish_button").set('style', "display:inline-block");
		dijit.byId("publish_button").set('disabled', true);
		dijit.byId("unpublish_button").set('disabled', true);
		dijit.byId("unpublish_button").set('style', "display:none");
		dijit.byId("delete_button").set('disabled', true);

		dojo.byId("details_area").style.display = "none";
		dojo.byId("details_area").style.visibility = "hidden";
	}
}
